﻿using System;
using FlowCanvas;
using FlowCanvas.Nodes;
using LogSystem;
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class StepRecord : EventNode
    {
        [RequiredField, DelayedField]
        public BBParameter<string> eventName = "EventName";
        public BBParameter<int> eventStep = 0;

        private FlowOutput onReceived;
        
        public override string name {
            get { return base.name + string.Format(" [ <color=#DDDDDD>{0}-{1}</color> ]", eventName, eventStep); }
        }
        
        public override void OnPostGraphStarted() {
            Subscribe(graph.agent.gameObject.GetAddComponent<ParadoxNotion.Services.EventRouter>());
        }
        
        public override void OnGraphStoped() {
            var router = graph.agent.gameObject.GetComponent<ParadoxNotion.Services.EventRouter>();
            if ( router != null ) { UnSubscribe(router); }
        }

        protected void Subscribe(ParadoxNotion.Services.EventRouter router) {
            router.onCustomEvent += OnCustomEvent;
        }

        protected void UnSubscribe(ParadoxNotion.Services.EventRouter router) {
            router.onCustomEvent -= OnCustomEvent;
        }
        
        protected override void RegisterPorts()
        {
            AddFlowInput("start",OnStart);
            onReceived = AddFlowOutput("Received");
        }

        public void OnStart(Flow f)
        {
            BlueprintUtils.SendGuideRequest(int.Parse(eventName.value), eventStep.value);
        }
        
        void OnCustomEvent(string eventName, ParadoxNotion.IEventData msg) {
            if (eventName.Equals(this.eventName.value.Trim()+"-"+this.eventStep.value, System.StringComparison.OrdinalIgnoreCase)) 
            {
                onReceived.Call(new Flow());
            }
        }
    }
}